import datetime

from flask import Flask, render_template, request, session, g, redirect

import config
from exts import db, mail, redis_store, mongo
from modules.auth import bp as auth_module
from modules.account import bp as account_module
from flask_migrate import Migrate
from flask_mail import Message
from models import Account, Dept  # 导入才会让flask_migrate识别到进而建表或更新


app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
mail.init_app(app)
mongo.init_app(app)
migrate = Migrate(app, db)
# flask db init     # 第一次生成时才执行
# flask db migrate
# flask db upgrade

app.register_blueprint(auth_module)
app.register_blueprint(account_module)


# 拦截器
@app.before_request
def before_request():
    print('this is before_request...', request.path, session.get('user_id'), datetime.datetime.now())
    if request.path == '/auth' or request.path == '/auth/':
        return
    # user_id = session.get('user_id')
    # if not user_id:
    #     return redirect("/auth/")
    # # 查询用户
    # user = Account.query.get(user_id)
    # # 将用户放入全局
    # setattr(g, "user", user)


# @app.before_first_request
# def before_first_request():
#     print('this is before_first_request...', session['hello'], datetime.datetime.now())


@app.after_request
def after_request(response):
    print('this is after_request...', datetime.datetime.now())
    return response


@app.errorhandler(404)
def deal_error(msg):
    print(f'未找到请求路径:{request.path},{msg}')
    return "404"


@app.errorhandler(Exception)
def deal_other_error(msg):
    print(f'发现错误:{request.path},{msg}')
    return "500"


# 全局上下文
@app.context_processor
def all_context():
    # 所有环境都可以用这个'user'
    if hasattr(g, 'user'):
        return {'user': g.user}
    else:
        return {'user': None}


@app.route('/')
def hello_world():  # put application's code here
    name = 'Forest'
    # print()
    session['hello'] = 'world'
    redis_store.incr(request.remote_addr, 1)
    return render_template("index.html", name=name)  # 'I Love CHINA!'


@app.route('/email')
def sendEmail():
    msg = Message(subject='邮箱测试', recipients=['844826411@qq.com'], body='hello flask email.')
    mail.send(msg)
    return "it is ok."


if __name__ == '__main__':
    app.run()
